#joe up on this shit
import os, os.path
import sys
import mutagen
from audio import audio
from video import video
from misc import misc

#Takes in a filename, runs metadata on each file

def gather(filename):
  library = [] 
  for root, dirs, files in os.walk(filename):
    for file in files:
      data = metadata(os.path.join(root,file))
      if data: library.append(data)
      else: print "gathering information on file {0} has failed", str(os.path.join(root,file))
  return library

def metadata(filename):
  from video import IMDB_error
  try:
    if is_audio(filename):
      file = audio(filename)
    elif is_video(filename):
      file = video(filename)
    else:
      file = misc(filename)

    return file 
  except IMDB_error, (instance):
    print "There was an error looking up the IMDB info: " + instance.parameter 
    print "On the file: " + filename

def is_audio(filename):
  filetype = unicode(filename.split(".")[-1])
  if filetype in ("mp3,flac"): return True
  return False

def is_video(filename):
  filetype = unicode(filename.split(".")[-1])
  if filetype in ("avi,mp4,mkv,m4v"):return True
  return False

def store(data):
  import sqlite3, os, inspect
  conn = sqlite3.connect(str(os.path.dirname(inspect.getfile(inspect.currentframe()))) + ".organizersql")
  c = conn.cursor()
  for f in data:
    print "storing file:" + str(f)
    if f.filetype in ("mp3","flac"):
      print f.to_db()
      c.execute("create table if not exists audio (filename text, filetype text, title text, artist text, album text, tracknumber integer, bitrate integer)")
      c.execute('insert into audio values (?,?,?,?,?,?,?)', f.to_db())
    if f.filetype in ("avi","mp4","mkv"):
      c.execute("create table if not exists video (filename text, filetype text, title text, season integer, episode integer, e_title text, size integer)")
      c.execute("insert into video values (?,?,?,?,?,?,?)", f.to_db())
      print "stored file:" + str(f)
  conn.commit()
  c.close()

def print_db():
  import sqlite3, os, inspect
  conn = sqlite3.connect(str(os.path.dirname(inspect.getfile(inspect.currentframe()))) + ".organizersql")
  c = conn.cursor()
  c.execute('select * from audio order by filename')
  for row in c:
    print row
  c.execute('select * from video order by filename')
  for row in c:
    print row


def write(filepath):
  import shutil
  import sqlite3, os, inspect
  conn = sqlite3.connect(str(os.path.dirname(inspect.getfile(inspect.currentframe()))) + ".organizersql")
  c = conn.cursor()
  c.execute('select * from video order by filename')
  for row in c:
    if(row[2] and row[2] != "unkown"):
      if(row[5] != "NOT TV"):
        path = os.path.join(filepath,"video","tv",row[2],"Season " + str(row[3]))
        if not os.path.isdir(path):
          os.makedirs(path)
        path = os.path.join(path,row[2] + "-S" + str(row[3]) + "E" + str(row[4]) + "-" + row[5] + "." + row[1])
        if not os.path.isfile(path):
          shutil.copy2(row[0],path)
      else:
        path = os.path.join(filepath,"video","movies")
        if not os.path.isdir(path):
          os.makedirs(path)
        path = os.path.join(path,row[2] + "." + row[1])
        if not os.path.exists(path):
          shutil.copy2(row[0],path)
  c.execute('select * from audio order by filename')
  for row in c:
    try:
      u = "unkown"
      if(row[2] != u and row[3] != u and row[4] != u):
        path = os.path.join(filepath,"audio",row[3],row[4])
        if not os.path.isdir(path):
          os.makedirs(path)
        path = os.path.join(path,str(row[2]) +  "." + str(row[1]))
        if not os.path.exists(path):
          shutil.copy2(row[0],path)
    except:
       print "failed to write: " + row[0]
 

if __name__ == "__main__":
  import argparse

  parser = argparse.ArgumentParser(description='Organize your media files.')
  parser.add_argument('-r', action="store", dest="read_path")
  parser.add_argument('-w', action="store", dest="write_path")
  parser.add_argument('-p', action="store_true", default=False, dest="p")
  parsed = parser.parse_args()
  if parsed.read_path:
    store(gather(parsed.read_path))
  if parsed.write_path:
    write(parsed.write_path)
  if parsed.p:
    print_db()
